# from functools import total_ordering
# import dash
# from dash import dcc, html


# from sqlalchemy import func
# import pandas as pd
# import numpy as np


from datetime import date
from server import server
from models import db, StatisticsData
import plotly.graph_objects as go
from sqlalchemy import func


#画维修次数和完成率
def create_repair_count_chart():
    

    with server.app_context():
        # 查找最新的统计日期
        latest_date_row = db.session.query(func.max(StatisticsData.stat_date)).scalar()
        if not latest_date_row:
            # 如果没有统计数据，返回一个空图表
            return go.Figure()
        latest_date = latest_date_row

        # 使用最新日期过滤数据
        stats = db.session.query(StatisticsData).filter(
            StatisticsData.stat_date == latest_date
        ).all()
        org_names = [s.org_shortname_c for s in stats]
        repair_counts = [s.fault_count or 0 for s in stats]
        complete_rates = [
            round((s.repair_complete_rate or 0) * 100, 2) for s in stats
        ]
        total_count = sum(repair_counts)
        total_complete = sum([s.repair_complete_count or 0 for s in stats])
        total_rates = round(total_complete / total_count * 100, 2) if total_count > 0 else 0
        # 按维修次数降序排列
        combined = list(zip(org_names, repair_counts, complete_rates))
        combined.sort(key=lambda x: x[1], reverse=True)
        org_names, repair_counts, complete_rates = zip(*combined) if combined else ([], [], [])

    fig = go.Figure()
    fig.add_trace(go.Bar(
        x=org_names,
        y=repair_counts,
        width=0.4,  # 这里设置柱子的宽度，数值越小柱子越细
        
        marker_color='#3399ff',
        name='维修次数',
        text=repair_counts,
        textposition='auto',
        textfont={'color': 'white', 'size': 10}
    ))
    fig.add_trace(go.Scatter(
        x=org_names,
        y=complete_rates,
        name='维修完成率',
        mode='lines+markers',
        line={'color': '#ffffff', 'width': 1},
        marker={'size': 6, 'color': '#FF9F40'},
        yaxis='y2'
    ))
    fig.update_layout(
        title={
            'text': f"总维修次数:{total_count}次  总完成率:{total_rates}%",
            'font': {'size': 14, 'color': 'white'},
            'x': 0.5,
            'y': 0.98,
            'xanchor': 'center',
            'yanchor': 'top'
        },
        plot_bgcolor="#112360",
        paper_bgcolor="#112360",
        font=dict(color='white'),
        margin=dict(l=0, r=0, t=50, b=50),
        xaxis=dict(showgrid=False, tickangle=45, tickfont={'size': 10}),
        yaxis=dict(title='维修次数', showgrid=True, gridcolor='#333'),
        yaxis2=dict(
            title='维修完成率(%)',
            range=[0, 120],
            overlaying='y',
            side='right',
            showgrid=False,
            showticklabels=True,
            automargin=True
        ),
        showlegend=True,
        legend=dict(
            orientation='h',
            yanchor='bottom',
            y=0.9,
            xanchor='center',
            x=0.5,
            bgcolor='rgba(0,0,0,0)'
        )
    )
    return fig

#画保养次数
def create_maintain_count_chart():
    with server.app_context():
        latest_date_row = db.session.query(func.max(StatisticsData.stat_date)).scalar()
        if not latest_date_row:
            # 如果没有统计数据，返回一个空图表
            return go.Figure()
        latest_date = latest_date_row
        today = latest_date
        stats = db.session.query(StatisticsData).filter(
            StatisticsData.stat_date == today
        ).all()
        org_names = [s.org_shortname_c for s in stats]
        maintain_counts = [s.maintain_plan_count or 0 for s in stats]
        complete_counts = [s.maintain_complete_count or 0 for s in stats]
        complete_rates = [
            round((s.maintain_complete_rate or 0) * 100, 2) for s in stats
        ]
        total_count = sum(maintain_counts)
        total_complete = sum(complete_counts)
        total_rates = round(total_complete / total_count * 100, 2) if total_count > 0 else 0
        combined = list(zip(org_names, maintain_counts, complete_rates))
        combined.sort(key=lambda x: x[1], reverse=True)
        org_names, maintain_counts, complete_rates = zip(*combined) if combined else ([], [], [])

    fig = go.Figure()
    fig.add_trace(go.Bar(
        x=org_names,
        y=maintain_counts,
        width=0.4,  # 这里设置柱子的宽度，数值越小柱子越细
        
        marker_color='#7c6bd8',
        name='保养次数',
        text=maintain_counts,
        textposition='auto',
        textfont={'color': 'white', 'size': 10}
    ))
    fig.add_trace(go.Scatter(
        x=org_names,
        y=complete_rates,
        name='保养完成率',
        mode='lines+markers',
        line={'color': '#FFFFFF', 'width': 1},
        marker={'size': 6, 'color': '#FF9F40'},
        yaxis='y2'
    ))
    fig.update_layout(
        title={
            'text': f"总保养次数:{total_count}次  总完成率:{total_rates}%",
            'font': {'size': 14, 'color': 'white'},
            
            'x': 0.5,
            'y': 0.98,
            'xanchor': 'center',
            'yanchor': 'top'},
        plot_bgcolor="#112360",
        paper_bgcolor="#112360",
        font=dict(color='white',size=12),
        margin=dict(l=0, r=0, t=50, b=50),
        xaxis=dict(showgrid=False, tickangle=45, tickfont={'size': 10}),
        yaxis=dict(title='保养次数', showgrid=True, gridcolor='#333'),
        yaxis2=dict(
            title='保养完成率(%)',
            range=[0, 120],
            overlaying='y',
            side='right',
            showgrid=False,
            showticklabels=True,
            automargin=True
        ),
        showlegend=True,
        legend=dict(
            orientation="h",      # 水平排列
            yanchor="bottom",     # 以底部为锚点
            y=0.9,               # y=1为顶部，1.08可让图例在图表上方
            xanchor="center",     # 以中心为锚点
            x=0.5                 # 居中
        )
    )
    return fig

#画巡检次数
def create_inspection_count_chart():
    with server.app_context():
        latest_date_row = db.session.query(func.max(StatisticsData.stat_date)).scalar()
        if not latest_date_row:
            # 如果没有统计数据，返回一个空图表
            return go.Figure()
        latest_date = latest_date_row
        today = latest_date
        stats = db.session.query(StatisticsData).filter(
            StatisticsData.stat_date == today
        ).all()
        org_names = [s.org_shortname_c for s in stats]
        inspection_counts = [s.inspection_plan_count or 0 for s in stats]
        complete_counts = [s.inspection_complete_count or 0 for s in stats]
        complete_rates = [
            round((s.inspection_complete_rate or 0) * 100, 2) for s in stats
        ]
        total_count = sum(inspection_counts)
        total_complete = sum(complete_counts)
        total_rates = round(total_complete / total_count * 100, 2) if total_count > 0 else 0
        combined = list(zip(org_names, inspection_counts, complete_rates))
        combined.sort(key=lambda x: x[1], reverse=True)
        org_names, inspection_counts, complete_rates = zip(*combined) if combined else ([], [], [])

    fig = go.Figure()
    fig.add_trace(go.Bar(
        x=org_names,
        y=inspection_counts,
        width=0.4,  # 这里设置柱子的宽度，数值越小柱子越细
        
        marker_color='#3399ff',
        name='巡检次数',
        text=inspection_counts,
        textposition='auto',
        textfont={'color': 'white', 'size': 10}
    ))
    fig.add_trace(go.Scatter(
        x=org_names,
        y=complete_rates,
        name='巡检完成率',
        mode='lines+markers',
        # line={'color': '#FF9F40', 'width': 3},
        line={'color': '#ffffff', 'width': 1},
        marker={'size': 6, 'color': '#FF9F40'},
        yaxis='y2',
        
        
    ))
    fig.update_layout(
        title={
            'text': f"总巡检次数:{total_count}次  总完成率:{total_rates}%",
            'font': {'size': 14, 'color': 'white'},
            'x': 0.5,
            'y': 0.98,
            'xanchor': 'center',
            'yanchor': 'top'},
        plot_bgcolor="#112360",
        paper_bgcolor="#112360",
        font=dict(color='white'),
        margin=dict(l=0, r=0, t=50, b=50),
       
        xaxis=dict(showgrid=False, tickangle=45, tickfont={'size': 10}),
        yaxis=dict(title='巡检次数', showgrid=True, gridcolor='#333'),
        yaxis2=dict(
            title='巡检完成率(%)',
            range=[0, 120],
            overlaying='y',
            side='right',
            showgrid=False,
            showticklabels=True,
            automargin=True,
            
        ),
        showlegend=True,
        legend=dict(
            orientation="h",
            yanchor="bottom",
            y=0.9,
            xanchor="center",
            x=0.5,
            bgcolor='rgba(0,0,0,0)'
        )
    )
    return fig
  

